package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.DistanceUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单业务层
 *
 * @author wkh
 * @date 2024/6/18 11:25
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Value("${sky.shop.address}")
    private String shopAddress;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 提交订单
     */
    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        // 判断地址是否为空
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        // 判断地址是否处于配送范围内
        String userAddress = addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail();
        double distance = DistanceUtil.getDistance(shopAddress, userAddress);
        if (distance > 5000.0) {
            throw new OrderBusinessException("超出配送范围");
        }

        // 判断购物车是否为空
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(BaseContext.getCurrentId());
        List<ShoppingCart> list = shoppingCartMapper.shoppingCartList(shoppingCart);
        if (list == null || list.isEmpty()) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        // 构建订单数据
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, order);
        order.setPhone(addressBook.getPhone());
        order.setAddress(addressBook.getDetail());
        order.setConsignee(addressBook.getConsignee());
        order.setNumber(String.valueOf(System.currentTimeMillis()));
        order.setUserId(BaseContext.getCurrentId());
        order.setStatus(Orders.PENDING_PAYMENT);
        order.setPayStatus(Orders.UN_PAID);
        order.setOrderTime(LocalDateTime.now());

        // 保存订单数据
        orderMapper.insert(order);

        // 构造订单明细数据
        List<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCart cart : list) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(order.getId());
            orderDetails.add(orderDetail);
        }

        // 保存订单明细数据
        orderDetailMapper.insertBatch(orderDetails);

        // 清空购物车
        shoppingCartMapper.deleteByUserId(BaseContext.getCurrentId());

        // 封装返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(order.getId())
                .orderNumber(order.getNumber())
                .orderAmount(order.getAmount())
                .orderTime(order.getOrderTime())
                .build();

        // 给商家发送消息
        Map map = new HashMap();
        map.put("type", 1);
        map.put("orderId", order.getId());
        map.put("content", "您有一个新的订单，订单号：" + order.getNumber());
        webSocketServer.sendToAllClient(JSONObject.toJSONString(map));

        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }

    /**
     * 订单统计
     */
    @Override
    public OrderStatisticsVO countOrderStatus() {

        // 待接单
        Integer toBeConfirmed = orderMapper.countByStatus(Orders.TO_BE_CONFIRMED);
        // 待派送
        Integer confirmed = orderMapper.countByStatus(Orders.CONFIRMED);
        // 派送中
        Integer deliveryInProgress = orderMapper.countByStatus(Orders.DELIVERY_IN_PROGRESS);

        // 封装返回结果
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);

        return orderStatisticsVO;
    }

    /**
     * 条件搜索订单
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        List<OrderVO> orderVOList = orderMapper.pageQuery(ordersPageQueryDTO);
//        if (orderVOList != null && !orderVOList.isEmpty()) {
            orderVOList.forEach(orderVO -> {
                StringBuilder dishesName = new StringBuilder();
                List<OrderDetail> orderDetailList =orderDetailMapper.getByOrderId(orderVO.getId());
                orderVO.setOrderDetailList(orderDetailList);
                for (OrderDetail orderDetail : orderDetailList) {
                    dishesName.append(orderDetail.getName()).append("*").append(orderDetail.getNumber()).append(";");
                }
                orderVO.setOrderDishes(dishesName.toString());
            });
            Page<OrderVO> page = (Page<OrderVO>) orderVOList;
            return new PageResult(page.getTotal(), page.getResult());
//        }
//        return null;
    }

    /**
     * 查询订单详情
     */
    @Override
    public OrderVO getOrderDetailsByOrderId(Long id) {
        Orders order = orderMapper.getById(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order, orderVO);
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);
        orderVO.setOrderDetailList(orderDetailList);
        StringBuilder dishesName = new StringBuilder();
        for (OrderDetail orderDetail : orderDetailList) {
            dishesName.append(orderDetail.getName()).append("*").append(orderDetail.getNumber()).append(";");
        }
        orderVO.setOrderDishes(dishesName.toString());
        return orderVO;
    }

    /**
     * 订单取消
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        // 判断订单状态
        Orders order = orderMapper.getById(ordersCancelDTO.getId());
        int status = order.getStatus();
        if (status == Orders.CONFIRMED || status == Orders.DELIVERY_IN_PROGRESS || status == Orders.COMPLETED || status == Orders.PENDING_PAYMENT) {
            // TODO 退款
            //weChatPayUtil.refund(order.getNumber(), order.getNumber(), order.getAmount(), order.getAmount());
            Orders orders = Orders.builder()
                    .id(ordersCancelDTO.getId())
                    .status(Orders.CANCELLED)
                    .cancelReason(ordersCancelDTO.getCancelReason())
                    .cancelTime(LocalDateTime.now())
                    .build();
            orderMapper.update(orders);
        } else {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
    }

    /**
     * 订单完成
     */
    @Override
    public void complete(Long id) {
        // 判断订单状态
        int status = orderMapper.getById(id).getStatus();
        if (status == Orders.DELIVERY_IN_PROGRESS) {
            // 更新订单状态
            Orders orders = Orders.builder()
                    .id(id)
                    .status(Orders.COMPLETED)
                    .deliveryTime(LocalDateTime.now())
                    .build();
            orderMapper.update(orders);
        } else {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
    }

    /**
     * 订单拒绝
     */
    @Override
    public void reject(OrdersRejectionDTO ordersRejectionDTO) {
       // 判断订单状态
        int status = orderMapper.getById(ordersRejectionDTO.getId()).getStatus();
       // 修改订单状态
        if (status == Orders.TO_BE_CONFIRMED) {
            // TODO 退款
            Orders orders = Orders.builder()
                    .id(ordersRejectionDTO.getId())
                    .status(Orders.CANCELLED)
                    .rejectionReason(ordersRejectionDTO.getRejectionReason())
                    .cancelTime(LocalDateTime.now())
                    .build();
            orderMapper.update(orders);
        } else {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
    }

    /**
     * 接单
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        // 判断订单状态
        int status = orderMapper.getById(ordersConfirmDTO.getId()).getStatus();
        // 修改订单状态
        if (status == Orders.TO_BE_CONFIRMED) {
            Orders orders = Orders.builder()
                    .id(ordersConfirmDTO.getId())
                    .status(Orders.CONFIRMED)
                    .build();
            orderMapper.update(orders);
        } else {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
    }

    /**
     * 派送订单
     */
    @Override
    public void delivery(Long id) {
        // 判断订单状态
        int status = orderMapper.getById(id).getStatus();
        // 修改订单状态
        if (status == Orders.CONFIRMED) {
            Orders orders = Orders.builder()
                    .id(id)
                    .status(Orders.DELIVERY_IN_PROGRESS)
                    .build();
            orderMapper.update(orders);
        } else {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
    }

    /**
     * 再来一单
     */
    @Override
    public void repetition(Long id) {
        // 查询订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);
        // 插入到购物车
        if (orderDetailList != null && !orderDetailList.isEmpty()) {
            orderDetailList.forEach(orderDetail -> {
                // TODO 购物车是否存在，菜品是否存在
                if(orderDetail.getDishId() != null) {
                    Dish dish = dishMapper.getById(orderDetail.getDishId());
                    if (dish != null && dish.getStatus() == 1) {
                        ShoppingCart shoppingCart = new ShoppingCart();
                        BeanUtils.copyProperties(orderDetail, shoppingCart, "id");
                        shoppingCart.setUserId(BaseContext.getCurrentId());
                        shoppingCart.setCreateTime(LocalDateTime.now());
                        shoppingCartMapper.insert(shoppingCart);
                    }
                } else if (orderDetail.getSetmealId() != null) {
                    Setmeal setmeal = setmealMapper.getById(orderDetail.getSetmealId());
                    if (setmeal != null && setmeal.getStatus() == 1) {
                        ShoppingCart shoppingCart = new ShoppingCart();
                        BeanUtils.copyProperties(orderDetail, shoppingCart, "id");
                        shoppingCart.setUserId(BaseContext.getCurrentId());
                        shoppingCart.setCreateTime(LocalDateTime.now());
                        shoppingCartMapper.insert(shoppingCart);
                    }
                }
            });
        }
    }

    /**
     * 用户催单
     */
    @Override
    public void reminder(Long id) {
        Orders orders = orderMapper.getById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        Map map = new HashMap();
        map.put("type",2);
        map.put("orderId",id);
        map.put("content","订单号：" + orders.getNumber());

        //通过websocket向商家浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }
}
